package cn.nawang.ebeim.client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.bean.NetWorkConnectResultBean;
import cn.nawang.ebeim.client.bean.NetWorkMonitorBean;
import cn.nawang.ebeim.client.util.NetWorkMonitorDbUtil;

/**
 * @ClassName: NetWorkMonitorThread
 * @Description: TODO
 * @author fanyb
 * @date Nov 18, 2015 3:53:52 PM
 * @version v1.0
 */
public class NetWorkMonitorThread implements Runnable {
  private static final Logger LOG = LoggerFactory.getLogger(NetWorkMonitorThread.class);
  private static String URL = "http://demo.ebeim.com";
  private static long ONEMINUTE = 60000;

  @Override
  public void run() {
    // 每隔一分钟发一次请求
    List<NetWorkConnectResultBean> list = new ArrayList<NetWorkConnectResultBean>();
    while (true) {
//      list.add(connected(storageServer.getHost(),storageServer.getPort()));
      list.add(connected(URL));
      try {
        Thread.sleep(ONEMINUTE);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      // 毎五条做一次记录
      if (list.size() == 5) {
        NetWorkMonitorBean netWorkMonitorBean = generateNetWorkConnectResultBean(URL, list);
        saveNetWorkMonitorBean(netWorkMonitorBean);
        list.removeAll(list);
      }
    }
  }

  private NetWorkConnectResultBean connected(String url) {
    NetWorkConnectResultBean result = new NetWorkConnectResultBean();
    result.setStartTime(new Date().getTime());
    result.setResult(testNewWorkConnected(url));
    result.setEndTime(new Date().getTime());
    LOG.info("connected result: {}", result);
    return result;
  }

  /**
   * 
   * @author fanyb
   * @Description: 启动网络连接
   * @param url
   * @return boolean
   * @date Nov 18, 20154:02:56 PM
   *
   * @修改人
   * @修改日期
   */
  private boolean testNewWorkConnected(String url) {
    try {
      URL localURL = new URL(url);
      URLConnection connection = openConnection(localURL);
      HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
      httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
      httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      httpURLConnection.getResponseCode();
      return true;
    } catch (IOException ioe) {
      ioe.printStackTrace();
      return false;
    }
  }

  private URLConnection openConnection(URL localURL) throws IOException {
    URLConnection connection;
    connection = localURL.openConnection();
    return connection;
  }

  private void saveNetWorkMonitorBean(NetWorkMonitorBean netWorkMonitorBean) {
    NetWorkMonitorDbUtil.addNetWorkMonitorBean(netWorkMonitorBean);
  }

  private NetWorkMonitorBean generateNetWorkConnectResultBean(String url,
      List<NetWorkConnectResultBean> list) {
    NetWorkMonitorBean netWorkMonitorBean = new NetWorkMonitorBean();
    int failCount = 0;
    double packetLossRate = 0;
    long totalTime = 0;
    String status = "false";
    for (NetWorkConnectResultBean netWork : list) {
      if (!netWork.isResult()) {
        failCount++;
      } else {
        totalTime += netWork.getEndTime() - netWork.getStartTime();
      }
    }
    packetLossRate = failCount / list.size();
    if (failCount != list.size()) {
      status = "true";
    }
    long averageTime = totalTime / (list.size() - failCount) / 2;
    netWorkMonitorBean.setPacketLossRate(packetLossRate);
    netWorkMonitorBean.setAverageTime(averageTime);
    netWorkMonitorBean.setStatus(status);
    netWorkMonitorBean.setUrl(url);
    return netWorkMonitorBean;
  }
}
